#include "search.h"



void search_file(char dirpath[num], const char *type,D_list *List_Head)
{
	Stack * top=create_stack(" ");
	push(top,dirpath);
	char path[num]={0};
	DIR *dir = NULL;
	struct dirent *ddir = NULL;//保存目录下每一项信息
	
	//打开文件保存查找到的数据
	FILE *file = fopen("./.path", "w+");
	if(file == NULL) return ;
	printf("searching...\n");
	while(!(pop(top, path)))
	{
		dir = opendir(path);
		if(dir == NULL) continue;//当目录打开失败，从新再从栈中取一个目录
		while((ddir = readdir(dir)) != NULL)
		{
			//判断是否是目录（除.	..）			
			if(ddir->d_type == DT_DIR && strcmp(ddir->d_name, ".") != 0 &&
			 strcmp(ddir->d_name, "..") != 0)	//dir
			{
				char tmp[num];
				strcpy(tmp, path);	//tmp =/home/gec
				if(strcmp(path,"/")!=0&&strcmp(path,"./")!=0)
				strcat(tmp,"/");	//tmp =/home/gec/
				strcat(tmp,ddir->d_name); //tmp=/home/gec/dir
				//把目录压入栈
				// printf("%s\n",tmp );
				push(top, tmp);
			}
			
			if(strstr(ddir->d_name, type))
			{
				//printf("%s/%s\n", path, ddir->d_name);
				//把找到的路径打包保存到文件filepath中
				char buf[num];
				sprintf(buf,"%s/%s", path, ddir->d_name);
				insert_into_kernel_link(List_Head,buf);
				fputs(buf, file);

			}
		}
		closedir(dir);
	}
	fclose(file);
}

